<template>
  <el-card style="margin:20px">
    
    <el-form :inline="true">
      <el-form-item>
        <el-input size="small" v-model="username" placeholder="用户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" icon="el-icon-search" @click="getAclListTotal()">查询</el-button>
        <el-button type="reset" size="small" @click="resetSearch()">清空</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" size="small" @click="addShow">添加</el-button>
    <el-button type="danger" size="small" @click="removeAll" :disabled="!userSelectTable.length > 0">批量删除</el-button>


    <el-table :data="aclList" border ref="multipleTable" :stripe="true" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" select>
      </el-table-column>
      <el-table-column align="center" width="80" type="index" label="序号"></el-table-column>
      <el-table-column width="180" align="center" label="用户名" prop="username"></el-table-column>
      <el-table-column label="用户昵称" prop="nickName"></el-table-column>
      <el-table-column width="180" label="角色列表" prop="roleName"></el-table-column>
      <el-table-column width="180" label="创建时间" prop="gmtCreate"></el-table-column>
      <el-table-column width="180" label="更新事件" prop="gmtModified"></el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="info" icon="el-icon-user" size="mini" @click="getAclData(scope.row)"></el-button>
          <el-button type="primary" icon="el-icon-edit-outline" size="mini" @click="editShow(scope.row)"></el-button>

          <!-- 单条删除显示起泡框 -->
          <el-popconfirm confirm-button-text='好的' cancel-button-text='不用了' icon="el-icon-delete-solid" icon-color="red"
            @onConfirm="removeOnAcl(scope.row.id)" :title="`确定要删除${scope.row.username}吗`">
            <el-button type="danger" icon="el-icon-delete" size="mini" slot="reference" style="margin-left:10px">
            </el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>


    <el-pagination @size-change="handleSizeChange" @current-change="getAclListTotal" :current-page="page"
      :page-sizes="[5, 9, 14]" :page-size="limit" layout="prev, pager, next,jumper, -> , sizes,total" :total="total">
    </el-pagination>


    <!-- 弹出添加修改对话框 -->
    <el-dialog :title="userForm.id ? '修改用户' : '添加用户'" :visible.sync="dialogFormVisible" destroy-on-close>
      <el-form :model="userForm" inline label-width="140px" :rules="rules" ref="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input size="small" v-model="userForm.username" autocomplete="off" style="width:400px"></el-input>
        </el-form-item>

        <el-form-item label="用户昵称">
          <el-input size="small" v-model="userForm.nickName" autocomplete="off" style="width:400px"></el-input>
        </el-form-item>

        <el-form-item label="用户密码" prop="password" v-if="!userForm.id">
          <el-input size="small" v-model="userForm.password" autocomplete="off" style="width:400px"></el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('userForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 弹出设置角色对话框 -->

    <el-dialog title="设置角色" :visible.sync="dialogSetupVisible" destroy-on-close>
      <el-form inline label-width="80px">
        <el-form-item label="用户名">
          <el-input size="small" v-model="userForm.username" autocomplete="off" disabled style="width:400px"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <div style="width:600px">
            <el-checkbox :indeterminate="(assignRoles.length > 0 && assignRoles.length < allRolesList.length)"
              v-model="checkAll" @change="handleCheckAllChange">全选
            </el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="assignRoles" @change="handleCheckedAssignRolesChange">
              <el-checkbox v-for="role in allRolesList" :label="role.id" :key="role.id">{{role.roleName}}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addAssignRoles(userForm.id)">确 定</el-button>
        <el-button @click="dialogSetupVisible = false">取 消</el-button>
      </div>

    </el-dialog>

  </el-card>




</template>
<script>
import store from '@/store';
import { mapState } from 'vuex';
export default {
  name: 'User',
  data() {
    return {
      username: "",
      page: 1,
      limit: 5,
      dialogFormVisible: false,
      userForm: {
        id: undefined,
        username: "",
        nickName: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: '请填写用户名', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 5 个字符', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
      },
      userSelectTable: [],
      dialogSetupVisible: false,
      checkAll: false,
      assignRoles: []
    };
  },
  methods: {
    // 获取所有信息 // 模糊查询
    async getAclListTotal(page = this.page) {
      let { limit } = this
      let searchName = { username: this.username }
      await store.dispatch("acluser/getAclListTotal", { page, limit, searchName })
    },
    // 分页
    handleSizeChange(val) {
      this.limit = val
      this.getAclListTotal(this.page)
    },
    // 重置
    resetSearch() {
      this.username = ""
      this.getAclListTotal()
    },
    // 添加按钮点击
    addShow() {
      this.userForm = {
        id: undefined,
        username: "",
        nickName: "",
        password: "",
      }
      this.dialogFormVisible = true;
    },
    // 修改按钮点击
    editShow(row) {
      this.userForm = ({ ...row })
      this.dialogFormVisible = true;
    },
    // 取消添加获修改
    submitForm(userForm) {
      this.$refs[userForm].validate(async (valid) => {
        // 表单验证通过valid才是true
        let userId = this.userForm?.id;
        if (valid) {
          await store.dispatch("acluser/saveAclOrUpdate", this.userForm)
          if (userId) {
            alert('修改成功!');
          } else {
            alert('添加成功!');
          }
          this.dialogFormVisible = false;
          this.getAclListTotal()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 点击表格多选,返回多选条例
    handleSelectionChange(val) {
      this.userSelectTable = val.reduce((prve, item, index) => {
        prve.push(item.id)
        return prve
      }, [])
    },
    // 批量删除
    async removeAll() {
      try {
        await store.dispatch("acluser/removeAllAcl", this.userSelectTable)
        this.$message("全部删除成功");
        this.getAclListTotal()
      } catch (error) {
        this.$message("全部删除失败");
      }
    },
    // 单条删除
    async removeOnAcl(id) {
      try {
        await store.dispatch("acluser/removeOnAcl", id)
        this.$message.success("删除成功")
        this.getAclListTotal()
      } catch (error) {
        this.$message.info("删除失败")
      }
    },
    // 更具id获取角色数据
    async getAclData(row) {
      try {
        await store.dispatch("acluser/getAclData", row.id)
        this.userForm = ({ ...row })
        this.dialogSetupVisible = true
        this.assignRoles = store.getters.assignRoles?.map(item => item.id)
        // this.assignRoles.length > 0 ? this.isIndeterminate = true : this.isIndeterminate = false
        this.checkAll = this.assignRoles.length === this.allRolesList.length
        console.log(this.checkAll)

      } catch (error) {
        this.$message.info("获取角色信息失败")

      }
    },
    // 点击改变全部
    handleCheckAllChange(value) {
      let res = this.allRolesList.map(item => item.id)
      this.assignRoles = (value ? res : []);
      // indeterminate 属性用以表示 checkbox 的不确定状态，一般用于实现全选的效果
      this.isIndeterminate = false;
    },
    // 点击改变单个
    handleCheckedAssignRolesChange(value) {
      this.checkAll = value.length === this.allRolesList.length
      this.assignRoles = value
    },
    // 点击保存修改角色
    async addAssignRoles(userId) {
      try {
        let roleId = this.assignRoles
        await store.dispatch("acluser/setDoAssign", { userId, roleId })
        this.$message.success("保存角色信息成功")
        this.dialogSetupVisible = false
        this.getAclListTotal()
      } catch (error) {
        this.$message.info("保存角色信息失败")

      }
    }
  },
  mounted() {
    this.getAclListTotal() 
  },
  computed: {
    ...mapState("acluser", ["aclList", "total", "userAclList"]),
    allRolesList() { return store.getters.allRolesList },
  }
}
</script>

<style scoped>

</style>
